<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Carbon;
use Exception;

class ExampleController extends Controller
{
    public function index()
    {
        $status = [
            'status' => 'ok',
            'framework' => [
                'name' => 'Lumen',
                'version' => app()->version()
            ],
            'system' => [
                'php_version' => PHP_VERSION,
                'php_timezone' => date_default_timezone_get(),
                'server_time' => date('Y-m-d H:i:s'),
                'carbon_time' => Carbon::now()->format('Y-m-d H:i:s'),
                'timestamp' => time(),
                'memory_usage' => $this->getMemoryUsage(),
                'server_info' => php_uname(),
                'mysql_version' => $this->getMysqlVersion(),
                'redis_info' => $this->getRedisInfo()
            ],
            'timezone_info' => [
                'app_timezone' => config('app.timezone'),
                'mysql_timezone' => $this->getMysqlTimezone(),
                'mysql_time' => $this->getMysqlTime(),
                'system_timezone' => $this->getSystemTimezone()
            ],
            'services' => [
                'mysql' => $this->checkMysql(),
                'redis' => $this->checkRedis()
            ]
        ];

        return response()->json($status);
    }

    private function checkMysql()
    {
        try {
            DB::select('SELECT 1');
            return [
                'status' => 'ok',
                'message' => 'MySQL connection successful'
            ];
        } catch (Exception $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }

    private function checkRedis()
    {
        try {
            Redis::ping();
            return [
                'status' => 'ok',
                'message' => 'Redis connection successful'
            ];
        } catch (Exception $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }

    private function getMemoryUsage()
    {
        $memory = memory_get_usage(true);
        if ($memory < 1024) {
            return $memory . ' B';
        } elseif ($memory < 1048576) {
            return round($memory / 1024, 2) . ' KB';
        } else {
            return round($memory / 1048576, 2) . ' MB';
        }
    }

    private function getMysqlVersion()
    {
        try {
            $result = DB::select('SELECT VERSION() as version')[0];
            return $result->version;
        } catch (Exception $e) {
            return 'Unknown: ' . $e->getMessage();
        }
    }

    private function getMysqlTimezone()
    {
        try {
            $result = DB::select("SELECT @@global.time_zone as global_tz, @@session.time_zone as session_tz");
            return [
                'global' => $result[0]->global_tz,
                'session' => $result[0]->session_tz
            ];
        } catch (Exception $e) {
            return 'Error: ' . $e->getMessage();
        }
    }

    private function getMysqlTime()
    {
        try {
            $timestamp = time();
            $now = Carbon::now();
            
            return [
                'php_time' => [
                    'timestamp' => $timestamp,
                    'formatted' => date('Y-m-d H:i:s'),
                    'timezone' => date_default_timezone_get()
                ],
                'carbon_time' => [
                    'formatted' => $now->format('Y-m-d H:i:s'),
                    'timezone' => $now->getTimezone()->getName()
                ],
                'mysql_time' => [
                    'current_timestamp' => DB::select("SELECT CURRENT_TIMESTAMP() as time")[0]->time,
                    'unix_timestamp' => DB::select("SELECT UNIX_TIMESTAMP() as time")[0]->time,
                    'converted_timestamp' => DB::select("SELECT FROM_UNIXTIME(?) as time", [$timestamp])[0]->time,
                    'timezone_info' => DB::select("SELECT @@session.time_zone as timezone")[0]->timezone
                ]
            ];
        } catch (Exception $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }

    private function getRedisInfo()
    {
        try {
            $info = Redis::info();
            return [
                'version' => $info['redis_version'] ?? 'unknown',
                'uptime' => $info['uptime_in_seconds'] ?? 0,
                'connected_clients' => $info['connected_clients'] ?? 0,
                'used_memory_human' => $info['used_memory_human'] ?? 'unknown'
            ];
        } catch (Exception $e) {
            return 'Error: ' . $e->getMessage();
        }
    }

    private function getSystemTimezone()
    {
        return [
            'system_timezone' => exec('date +%Z'),
            'system_offset' => exec('date +%z'),
            'system_time' => exec('date "+%Y-%m-%d %H:%M:%S"')
        ];
    }
}